package com.jyu.apts.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.jyu.apts.dto.ResultDto;
import com.jyu.apts.dto.UserDto;
import com.jyu.apts.entity.User;

@RestController
public class LoginController {
	
	@RequestMapping("/login")
	public ModelAndView login(User user) {
		ModelAndView mv = new ModelAndView();
		String username=user.getUsername();
		String password=user.getPassword();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password,false);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
		} catch(IncorrectCredentialsException e){
			mv.addObject("msg", "密码错误");
			mv.setViewName("/login.html");
			return mv;
		} catch (AuthenticationException e) {
			mv.addObject("msg", "登录失败");
			mv.setViewName("/login.html");
			return mv;
		}		
		
		mv.addObject("userDto",(UserDto)subject.getSession().getAttribute("userDto"));
		mv.setViewName("/index.html");
		return mv;
	}
	
	@RequestMapping("/login_html")
	public ModelAndView login() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/login.html");
		return mv;
	}
	
	@RequestMapping("/logout")
	public ModelAndView logout() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/login.html");
		return mv;
	}
	
	@RequestMapping("/logoutWithResult")
	public ResultDto logoutWithResult() {
		return new ResultDto("退出登陆",null,0);
	}
}
